﻿using System.Collections.Generic;
using ZYing.LiquidThemeEngine.Paginating;

// ReSharper disable InconsistentNaming

namespace ZYing.LiquidThemeEngine.Objects
{
    public class Paginate
    {
        public Paginate(PaginationValue value)
        {
            var source = value.Source;
            Items = value.Total;
            CurrentOffset = (source.CurrentPage - 1) * value.PageSize;
            CurrentPage = source.CurrentPage;
            PageSize = value.PageSize;
            Pages = Items / PageSize;
            if (Items % PageSize > 0) Pages++;


            if (Pages > 1)
            {
                //上一页

                if (CurrentPage > 1)
                    Previous = new PaginatePart
                    {
                        IsLink = true,
                        Title = SR.Paginate_Previous_Title,
                        Url = source.GetUrl(CurrentPage - 1)
                    };

                //后一页

                if (CurrentPage < Pages)
                    Next = new PaginatePart
                    {
                        IsLink = true,
                        Title = SR.Paginate_Next_Title,
                        Url = source.GetUrl(CurrentPage + 1)
                    };

                var min = CurrentPage - 2L;
                var max = CurrentPage + 2L;
                if (min <= 1) min = 2;

                if (max >= Pages) max = Pages - 1;

                var last = 0;
                for (var page = 1; page <= Pages; page++)
                {
                    var add = false;
                    if (page == 1)
                        add = true;
                    else if (page == Pages)
                        add = true;
                    else if (page >= min && page <= max) add = true;

                    if (!add) continue;

                    if (last + 1 != page)
                        Parts.Add(new PaginatePart
                        {
                            IsLink = false,
                            Title = "…"
                        });

                    last = page;
                    var item = new PaginatePart
                    {
                        Title = page.ToString(),
                        IsLink = page != CurrentPage
                    };
                    if (item.IsLink) item.Url = source.GetUrl(page);

                    Parts.Add(item);
                }
            }
        }

        public int CurrentOffset { get; set; }
        public int CurrentPage { get; set; }
        public int Items { get; set; }
        public List<PaginatePart> Parts { get; } = new();
        public PaginatePart Previous { get; set; }
        public PaginatePart Next { get; set; }
        public int PageSize { get; set; }
        public int Pages { get; set; }

        public class PaginatePart
        {
            public bool IsLink { get; set; }
            public string Title { get; set; }
            public string Url { get; set; }
        }
    }
}